var StudentList = function () {
    let
        AUTHORITY = $("#authority").attr("content");
    var initTable = function () {
        // 渲染列表
        var oTable = $("#table_core")
            .DataTable(
                {
                    "bAutoWidth": true,
                    "scrollX": true,
                    // "bProcessing" : true,
                    "bFilter": false,
                    // "bStateSave" : true,
                    // "sPaginationType" : "full_numbers",
                    "aaSorting": [[0, 'desc']],
                    bSort: false,
                    "oLanguage": { // 汉化
                        "sProcessing": "正在加载数据...",
                        "sLengthMenu": "显示_MENU_条",
                        "sZeroRecords": "没有您要搜索的内容",
                        "sInfo": "从_START_ 到 _END_ 条记录——总记录数为 _TOTAL_ 条",
                        "sInfoEmpty": "记录数为0",
                        "sInfoFiltered": "(全部记录数 _MAX_  条)",
                        "sInfoPostFix": "",
                        "sSearch": "搜索",
                        "sUrl": "",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": " 上一页 ",
                            "sNext": " 下一页 ",
                            "sLast": " 末页 "
                        }
                    },
                    "aoColumns": [
                        {
                            "mData": function (source, type, val) {
                                return source;
                            },
                            "mRender": function (value, method, row) {
                                return '<span class="center"><input type="checkbox" value="'
                                    + value.id + '"></span>'
                            }
                        },
                        {
                            "mData": function (source, type, val) {
                                return source;
                            },

                            "mRender": function (value, method, row) {
                                return '<a id="stu_view" href="javascript:;" data-id="'
                                    + value.id
                                    + '">'
                                    + value.id
                                    + '<i class="icon-user icon-white"></i></a>'
                            }
                        },
                        {
                            "mData": "stuName",

                            "mRender": function (value, method, row) {
                                return '<input type="text" class="m-wrap small" value="'
                                    + value + '" id="stuName">'
                            }
                        },
                        {
                            "mData": "stuBirth"
                        },
                        {
                            "mData": "stuSex",
                            "mRender": function (value, method, row) {
                                return value == 1 ? "男" : "女";
                            }
                        },
                        {
                            "mData": "stuAge"
                        },
                        {
                            "mData": "stuParentName"
                        },
                        {
                            "mData": "stuPhone",
                            "mRender": function (value, method, row) {
                                return '<input type="text" class="m-wrap small" value="'
                                    + value
                                    + '" id="stuPhone">'
                            }
                        },
                        {
                            "mData": "stuState"
                        },
                        {
                            "mData": "stuMarketPerson"
                        },
                        {
                            "mData": "stuAffiliatedAdviser"
                        },
                        {
                            "mData": function (source, type, val) {
                                return source;
                            },
                            "sWidth": "160px",
                            "mRender": function (value, method, row) {
                                var btn = '';

                                let
                                    edit = '<a class="btn purple stu_edit" data-id="'
                                        + value.id
                                        + '" ><i class="icon-edit"></i> 编辑</a>';
                                let
                                    del = '<a class="btn red stu_delete" style="margin-left:5px;" data-id="'
                                        + value.id
                                        + '"><i class="icon-trash"></i> 删除</a>';

                                if (AUTHORITY
                                        .includes("PERMISSION_STUDENT_INFO_EDIT")) {
                                    btn += edit;
                                }
                                if (AUTHORITY
                                        .includes("PERMISSION_STUDENT_INFO_DELETE")) {
                                    btn += del;
                                }
                                return btn;
                            }
                        }],
                    bServerSide: true,
                    sAjaxSource: "/studentlist",
                    fnServerData: function (source, data, fnCallBack) {
                        // alert("data:"+JSON.stringify(data));
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            url: source,
                            data: "param=" + JSON.stringify(data) + "&" + $("#stu_core_search_form").serialize(),
                            // beforeSend:beginWait(),
                            success: function (d) {
                                if (d.retCode != "1")
                                // bootbox.alert(d.retMsg);
                                    alert(d.retMsg);
                                else {
                                    // $("#total").html(d.retObj.iTotalRecords);
                                    fnCallBack(d.retObj);
                                }
                            },
                            failure: function (d) {
                                // bootbox.alert("服务器无响应");
                                alert("服务器无响应");
                            },
                            // complete:clearWait()
                        });
                    }
                });

        jQuery('#table_core_wrapper .dataTables_filter input').addClass(
            "m-wrap small"); // modify table search input
        jQuery('#table_core_wrapper .dataTables_length select').addClass(
            "m-wrap small"); // modify table per page dropdown
        jQuery('#table_core_wrapper .dataTables_length select').select2(); // initialzie
        // select2
        // dropdown

        $("#table_core").on(
            "blur",
            "td input#stuName",
            function (e) {
                e.preventDefault();
                //
                let
                    post_data = oTable.row($(this).parents('tr')).data();
                post_data.stuName = $(this).val();
                submitForm(JSON.stringify(post_data), "PUT", "/student/"
                    + post_data.id);
            });

        $("#table_core").on(
            "blur",
            "td input#stuPhone",
            function (e) {
                e.preventDefault();
                //
                let
                    post_data = oTable.row($(this).parents('tr')).data();
                post_data.stuPhone = $(this).val();
                submitForm(JSON.stringify(post_data), "PUT", "/student/"
                    + post_data.id);
            });

        //3.表格数据查询
        $("#btn_tbl_search").click(function (e) {
            e.preventDefault();

            let birthFrom = $("#birthFrom").val();
            let birthTo = $("#birthTo").val();


            if (birthFrom&&birthFrom!="" && birthTo&&birthTo!="") {

                if(birthFrom>birthTo){
                    layer.msg("亲，日期范围不正确！", {
                        icon: 2
                    });

                    return;
                }

            }

            oTable.draw(true);

        });
        $("#btn_core_refresh").click(function () {

            $("#stu_core_search_form button[type='reset']").trigger("click");//触发reset按钮
            oTable.draw(true);
        });
    };

    var event = function () {
        //1.添加学员
        $("#btn_submit").click(function (e) {
            e.preventDefault();

            var $form = $("#stu_add_form");

            // alert($("#txtStuName").val());
            if (!$("#txtStuName").val()) {
                layer.msg("亲，学员姓名不能为空！", {
                    icon: 2
                });
                return;
            }

            var form_data = $form.serializeArray();
            var post_data = {};

            $.map(form_data, function (n, i) {

                var key = n['name'];
                var value = n['value'];
                if (key && post_data.hasOwnProperty(key)) {
                    let
                        originValue = post_data[key];
                    let
                        newValue = originValue + "," + value;
                    post_data[key] = newValue;
                } else {
                    post_data[key] = value;
                }

            });

            submitForm(JSON.stringify(post_data), "POST", "/studentadd");
            window.location.reload();
        });
        // 2.单个删除学员信息
        $("#table_core").on("click", "td a.stu_delete", function () {
            var roleId = $(this).attr("data-id");
            layer.confirm('您确定要删除吗，删除后不可恢复？', {
                title: '删除学员',
                btn: ['是', '否'],
                btnAlign: 'c'
                // 按钮
            }, function () {
                var stuIds = [];
                stuIds.push(roleId);
                deleteStudent(JSON.stringify(stuIds));
            }, function () {
                layer.msg('取消删除！', {
                    icon: 2
                });
            });
        });
        // 3.查看学员信息
        $("#table_core").on("click", "td a#stu_view", function () {
            var roleId = $(this).attr("data-id");
            layer.open({
                title: '查看学员信息',

                type: 2,
                skin: 'layui-layer-lan', // 加上边框
                // area: ['620px', 'auto'], //宽高
                area: ["80%", "70%"],
                scrollbar: false, // 父页面 滚动条 禁止
                content: "/student/" + roleId,

            });

        });

        // 4.编辑
        $("#table_core").on(
            "click",
            "td a.stu_edit",
            function () {
                var roleId = $(this).attr("data-id");
                // 页面层
                layer.open({
                    title: '编辑学员信息',
                    btn: ['是', '否'],
                    type: 2,
                    // skin: 'layui-layer-lan', //加上边框
                    // area: ['620px', 'auto'], //宽高
                    scrollbar: false, // 父页面 滚动条 禁止
                    area: ["95%", "90%"],
                    content: "/studentedit/" + roleId,
                    anim: 1,
                    yes: function (index, layerno) {
                        var body = layer.getChildFrame('body', index);
                        var $posName = body.find("#txtStuName");
                        var $form = body.find("#stu_edit_form");

                        if (!$posName.val()) {
                            layer.msg("亲，学员姓名不能为空！", {
                                icon: 2
                            });
                            return;
                        }

                        var form_data = $form.serializeArray();
                        var post_data = {};

                        $.map(form_data, function (n, i) {

                            var key = n['name'];
                            var value = n['value'];
                            if (key && post_data.hasOwnProperty(key)) {
                                let
                                    originValue = post_data[key];
                                let
                                    newValue = originValue + "," + value;
                                post_data[key] = newValue;
                            } else {
                                post_data[key] = value;
                            }

                        });
//							alert(JSON.stringify(post_data));

                        submitForm(JSON.stringify(post_data), "PUT", "/studentedit/" + roleId);

                    },
                    btn2: function (index, layerno) {
                        layer.msg("取消了", {
                            icon: 2
                        });
                    }
                });
            });

        //5.全选
        $("#checkAll").click(function () {

            if ($(this).is(':checked')) {
                // alert("全选");
                $("#table_core input[type='checkbox']").prop("checked", "checked");
            } else {
                // alert("没选");
                $("#table_core input[type='checkbox']").removeAttr("checked");
            }
        });

        //6.批量删除
        $("#btn_core_batch").click(function (e) {
            e.preventDefault();
            var valArr = new Array();
            $("#table_core tbody input[type='checkbox']").each(function (i) {
                if ($(this).is(':checked')) {
                    valArr.push($(this).val());
                }
            });
            if (valArr.length == 0) {
                layer.msg("请至少选中一个学员！", {icon: 2});
                return;
            }
            layer.confirm('您确定要删除吗，删除后不可恢复？', {
                title: '删除学员',
                btn: ['是', '否'],
                btnAlign: 'c'
                // 按钮
            }, function () {
                //执行批量删除
                deleteStudent(JSON.stringify(valArr));
            });

        });
        //7.批量修改市场人员
        $("#btn_update_batch").click(function (e) {
            e.preventDefault();
            var valArr = new Array();
            $("#table_core input[type='checkbox']").each(function (i) {
                if ($(this).is(':checked')) {
                    valArr.push($(this).val());
                }
            });
            if (valArr.length == 0) {
                layer.msg("请至少选中一个学员！", {icon: 2});
                return;
            }
            var marketId = $("#batch_market_person").val();

            var post_data = {};
            post_data.ids = valArr;
            post_data.personId = marketId;
            submitForm(JSON.stringify(post_data), "PUT", "/studentmarket");

        });
    };

    function deleteStudent(data) {
        $
            .ajax({
                type: "POST",
                dataType: "json",
                url: "/studentdelete",
                contentType: "application/json;charset=utf-8",
                data: data
            })
            .done(
                function (data) {
                    if (data && data.retCode == 1) {
                        layer.msg("恭喜您，删除成功！", {
                            icon: 1
                        });
                        setTimeout(
                            'layer.closeAll();$("#table_core").DataTable().ajax.reload();',
                            800)

                    } else {
                        var s = layer.msg("对不起，删除失败！", {
                            icon: 2
                        });
                        layer.close(s);
                    }

                }).fail(function (d) {
            layer.msg("服务器无响应", {
                icon: 2
            });

        });
    }

    /**
     * 提交表单
     *
     * @param data
     */
    function submitForm(data, type, url) {
        $.ajax({
            type: type,
            dataType: "json",
            url: url,
            contentType: "application/json;charset=utf-8",
            data: data
        })
            .done(
                function (data) {
                    if (data && data.retCode == 1) {
                        layer.msg(data.retMsg, {
                            icon: 1
                        });
                        setTimeout(
                            'layer.closeAll();$("#table_core").DataTable().ajax.reload();',
                            1000)

                    } else {
                        var s = layer.msg("对不起，添加失败！", {
                            icon: 3
                        });
                        layer.close(s);
                    }

                }).fail(function (d) {
            layer.msg("服务器无响应");

        });
    }

    return {
        init: function () {

            initTable();
            event();
        }
    };

}();